# -*- coding: utf-8 -*-
"""
@Time    : 2020/11/20
@Author  : xinghen
@File    : nh_topsis_utils.py
"""
import numpy as np
import xlrd
import pandas as pd
import numpy as np
import xlrd
import pandas as pd

# 权重
w = np.array([0.1806, 0.1810, 0.3064, 0.332])

# datafile = 'data.xlsx'
resultfile = 'result.xlsx'


class NhTopsisUtil:
    # 从excel文件中读取数据
    def read(self, file):
        wb = xlrd.open_workbook(filename=file)  # 打开文件
        sheet = wb.sheet_by_index(0)  # 通过索引获取表格
        rows = sheet.nrows  # 获取行数
        all_content = []  # 存放读取的数据
        for j in range(1, 5):  # 取第1~第4列对的数据
            temp = []
            for i in range(1, rows):
                cell = sheet.cell_value(i, j)  # 获取数据
                temp.append(cell)
            all_content.append(temp)  # 按列添加到结果集中
            temp = []
        return np.array(all_content)

    def temp2(self, datas):
        K = np.power(np.sum(pow(datas, 2), axis=0), 0.5)
        for j in range(K.size):
            datas[:, j] = datas[:, j] / K[j]
        return datas

    def temp3(self, sta_data, w):
        z_max = np.amax(sta_data, axis=0)
        z_min = np.amin(sta_data, axis=0)
        # 计算每一个样本点与最大值的距离
        tmpmaxdist = np.power(np.sum(np.multiply(np.power((z_max - sta_data), 2), w), axis=1), 0.5)  # 每个样本距离Z+的距离
        tmpmindist = np.power(np.sum(np.multiply(np.power((z_min - sta_data), 2), w), axis=1), 0.5)  # 每个样本距离Z+的距离
        score = tmpmindist / (tmpmindist + tmpmaxdist)
        score = score / np.sum(score)  # 归一化处理
        return score

    def topsis_cal(self, dim_gra_result, dim_weight, ):  # 通过topsis 计算数据结果

        dim_gra_df = pd.DataFrame()
        dim_gra_df_columns = []
        for dim_key in dim_gra_result.keys():
            dim_gra_df = pd.concat((dim_gra_df, dim_gra_result[dim_key]), axis=1)
            dim_gra_df_columns.append(dim_key)
        dim_gra_df.columns = dim_gra_df_columns
        dim_gra_df = dim_gra_df[dim_weight.columns]
        ori_df_inxs = dim_gra_df.index
        answer1 = dim_gra_df.values

        w = dim_weight.values
        # answer2 = np.array(answer1).transpose()  # 将list转换为numpy数组并转置
        answer2 = answer1  # 将list转换为numpy数组并转置
        answer3 = self.temp2(answer2)  # 数组正向化
        answer4 = self.temp3(answer3, w.T.ravel())  # 标准化处理去钢
        data = pd.DataFrame(answer4)  # 计算得分
        data = data.set_index(ori_df_inxs)
        data2 = data.apply(lambda X: X - X.min(), axis=0).apply(lambda X: (X / X.max()) * 100, axis=0)
        data = 100 + data2
        data = data.apply(lambda x: 100 * (x / x.max()), axis=0).sort_values(by=0, ascending=False)

        return data

        # 将得分输出到excel表格中
        # writer = pd.ExcelWriter(resultfile)  # 写入Excel文件
        # data.to_excel(writer, 'page_1', float_format='%.5f')  # ‘page_1’是写入excel的sheet名
        # writer.save()
        # writer.close()


if __name__ == '__main__':
    NhTopsisUtil().topsis_cal()
